package vn.vfriends.vbox.timer;

import java.util.List;
import javax.ejb.Schedule;
import javax.ejb.Singleton;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import vn.vfriends.vbox.facade.AccountFacade;
import vn.vfriends.vbox.model.Account;
import vn.vfriends.vbox.storage.GoogleDriveService;

/**
 *
 * @author tuancn
 */
@Singleton
public class RefreshTokenTimer {

    private static final Logger logger = LoggerFactory.getLogger(RefreshTokenTimer.class);
    
    @Inject
    private AccountFacade accountFacade;
    
    @Inject
    private GoogleDriveService googleDriveService;
    
    private static final int REMAINS_OF_TIME = 600; //  10 minutes
    
    @Schedule(minute="*/2", hour="*", persistent = false)
    public void refreshToken() {
        List<Account> accounts = this.accountFacade.findAccountsNeedRefreshToken(REMAINS_OF_TIME);
        for(Account account : accounts) {
            logger.info("Start refresh the access token of {}...", account.getOwnId());
            googleDriveService.refreshToken(account);
            logger.info("Finish refresh the access token of {}...", account.getOwnId());
        }
    }
}
